const vscode = require('vscode');
const path = require('path');
const Recorder = require('../browser/recorder');

function activate(context) {
    // 创建状态栏项
    const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
    statusBarItem.text = '$(record) MCP Recorder';
    statusBarItem.tooltip = 'Click to start/stop recording';
    statusBarItem.command = 'mcp.toggleRecording';
    statusBarItem.show();

    let recorder = null;
    let outputChannel = null;

    // 注册命令
    const toggleRecording = vscode.commands.registerCommand('mcp.toggleRecording', async () => {
        if (recorder) {
            await stopRecording();
        } else {
            await startRecording();
        }
    });

    context.subscriptions.push(toggleRecording, statusBarItem);

    async function startRecording() {
        try {
            // 获取用户输入URL
            const url = await vscode.window.showInputBox({
                prompt: 'Enter the URL to record',
                placeHolder: 'https://example.com'
            });

            if (!url) return;

            // 创建输出通道
            outputChannel = vscode.window.createOutputChannel('MCP Recorder');
            outputChannel.show();
            outputChannel.appendLine(`Starting recording for ${url}`);

            // 获取存储路径
            const workspaceFolders = vscode.workspace.workspaceFolders;
            const storagePath = workspaceFolders ? 
                path.join(workspaceFolders[0].uri.fsPath, 'mcp-recordings') :
                path.join(require('os').homedir(), 'mcp-recordings');

            // 初始化录制器
            recorder = new Recorder(storagePath);
            statusBarItem.text = '$(record) Recording...';
            statusBarItem.backgroundColor = new vscode.ThemeColor('statusBarItem.errorBackground');

            // 开始录制
            await recorder.startRecording(url);
            outputChannel.appendLine(`Recording started at ${new Date().toLocaleString()}`);

        } catch (error) {
            vscode.window.showErrorMessage(`Recording failed: ${error.message}`);
            console.error(error);
            recorder = null;
            statusBarItem.text = '$(record) MCP Recorder';
            statusBarItem.backgroundColor = undefined;
        }
    }

    async function stopRecording() {
        try {
            if (!recorder) return;

            statusBarItem.text = '$(record) Saving...';
            outputChannel.appendLine('Stopping recording...');

            // 停止录制
            const result = await recorder.stopRecording();
            recorder = null;

            statusBarItem.text = '$(record) MCP Recorder';
            statusBarItem.backgroundColor = undefined;

            outputChannel.appendLine(`Recording saved to: ${result.recordingDir}`);
            outputChannel.appendLine(`Recorded ${result.stats.apiCalls} API calls and ${result.stats.userActions} user actions`);

            vscode.window.showInformationMessage(
                'Recording completed!',
                'Open Folder'
            ).then(selection => {
                if (selection === 'Open Folder') {
                    vscode.commands.executeCommand('revealFileInOS', vscode.Uri.file(result.recordingDir));
                }
            });

        } catch (error) {
            vscode.window.showErrorMessage(`Failed to stop recording: ${error.message}`);
            console.error(error);
        }
    }
}

function deactivate() {
    if (recorder) {
        recorder.stopRecording().catch(console.error);
    }
}

module.exports = {
    activate,
    deactivate
};